package com.gage.print.pdf.util;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.Sides;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.icepdf.ri.common.PrintJobWatcher;

public class PrintUtil {
	private static final int COPIES = 1;

	public static PrintService[] searchAllPrintService() {
		return PrinterJob.lookupPrintServices();
	}

	public static PrintService getPrintService(String printServiceName) {
		PrintService[] allPrintServices = searchAllPrintService();
		for (PrintService ps : allPrintServices) {
			if (ps.getName().equals(printServiceName)) {
				return ps;
			}
		}
		return null;
	}

	public static void print(File printFile, PrintService printService) {

		// 打印参数设置
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		// 纵向
		pras.add(OrientationRequested.PORTRAIT);
		pras.add(Sides.TUMBLE);
		pras.add(new Copies(COPIES));

		// 开始打印
		try {
			PDDocument document = PDDocument.load(printFile);
			Book book = new Book();
			// 设置纸张及缩放
			PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
			PageFormat pageFormat = new PageFormat();
			// 设置打印方向
			pageFormat.setOrientation(PageFormat.LANDSCAPE);// 纵向
			pageFormat.setPaper(getPaper());// 设置纸张
			book.append(pdfPrintable, pageFormat, document.getNumberOfPages());

			Doc doc = new SimpleDoc(book, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
			DocPrintJob printJob = printService.createPrintJob();
			PrintJobWatcher pjDone = new PrintJobWatcher(printJob);
			
			printJob.print(doc, pras);

			// 监听直至完成
			pjDone.waitForDone();
		} catch (PrintException e) {
			e.printStackTrace();
		} catch (InvalidPasswordException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Paper getPaper() {
		Paper paper = new Paper();
		// 默认为A4纸张，对应像素宽和高分别为 595, 842
		int width = 595;
		int height = 842;
		// 设置边距，单位是像素，10mm边距，对应 28px
		int marginLeft = 10;
		int marginRight = 0;
		int marginTop = 10;
		int marginBottom = 0;
		paper.setSize(width, height);
		// 下面一行代码，解决了打印内容为空的问题
		paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight),
				height - (marginTop + marginBottom));
		return paper;
	}
}
